package exttable.testfiller.formcomponents;

import dbutils.DbUtils;
import exttable.SGTTestParametrs;
import exttable.dbclasses.DbFile;
import exttable.dbclasses.DbTable;
import exttable.dbclasses.DicGeneral;
import exttable.formgenerator.ComponentsToPanel;
import exttable.formgenerator.ListenerFactory;
import exttable.formgenerator.StaticMethods;
import exttable.testfiller.ComponentGenerator;
import exttable.testfiller.InputFormDisplay;
import exttable.testfiller.ValueVerifier;
import exttable.testselector.VolunteerSelectorController;
import exttable.testselector.VolunteerSelectorView;
import exttable.userdefineextendsclasses.userDefineJFileChooser.UserDefineJFileChooserWithView;
import exttable.view.ViewAnalysis;
import exttable.view.ViewTestComboBox;
import options.AppSettings;
import utils.Localisation;
import utils.UserFileFactory;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: Apr 7, 2010
 * Time: 10:25:35 PM
 * To change this template use File | Settings | File Templates.
 */
public class InputJComponents {
    static String tableName;


    public static JComponent getComponentTF(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {

        JTextField tf = new JTextField(5);
        tf.setName(rs.getString(1));
        tf.setInputVerifier(new ValueVerifier(rs.getString("minValue")
                , rs.getString("maximumValue")
                , rs.getString("validationType").equals("VALIDATION")
                , rs.getString("name_ru")
                , rs.getString("name_en")
                , rs.getString("name_kk")
                , tf.getName()));

        if (oldData != null) {
            String oldValue = getOldValue(rs.getString(1), oldData);
            tf.setText(oldValue);
        } else if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            tf.setText(oldValue);
        }
        return tf;
    }


    public static JComponent getComponentCB(final ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        tableName = rs.getString("TABLE_NAME");
        /*
        This method create JComboBox for medical tests.
         */
//        Connection s = DbUtils.getDBConnectionGeneral();
//        System.out.println(rs.getString("REFERENCE_TABLE"));
//        PreparedStatement ps = s.prepareStatement("SELECT * FROM dic_general WHERE dic_type='"+
//                rs.getString("REFERENCE_TABLE")+"'"+
//        "AND table_field='"+rs.getString("COLUMN_NAME")+"'"+
//        "AND table_name='"+rs.getString("TABLE_NAME")+"'");
//        System.out.println("ps: "+ps.toString());
//        ResultSet rs2 = ps.executeQuery();
//        List<ViewTestComboBox> list = new ArrayList<ViewTestComboBox>();
//        while (rs2.next()) {
//            ViewTestComboBox ctc = new ViewTestComboBox.Build()
//                    .id(rs2.getString(1))
//                    .nameRu(rs2.getString("name_ru"))
//                    .nameEn(rs2.getString("name_en"))
//                    .nameKz(rs2.getString("name_kk"))
//                    .build();
//            list.add(ctc);
//        }

        List<String> keyList = new ArrayList<String>();
        keyList.add(rs.getString("TABLE_NAME"));
        keyList.add(rs.getString("COLUMN_NAME"));
        keyList.add(rs.getString("REFERENCE_TABLE").toLowerCase());

        List<DicGeneral> listDicGeneral = VolunteerSelectorView.getMapDicGeneral().get(keyList);
        List<ViewTestComboBox> list = new ArrayList<ViewTestComboBox>();
        for (DicGeneral dicGeneral : listDicGeneral) {
            ViewTestComboBox ctc = new ViewTestComboBox.Build()
                    .id(String.valueOf(dicGeneral.getDicId()))
                    .nameRu(dicGeneral.getNameRu())
                    .nameEn(dicGeneral.getNameEn())
                    .nameKz(dicGeneral.getNameKz())
                    .build();
            list.add(ctc);
        }
        JComboBox toReturn = new JComboBox(list.toArray());
        toReturn.setName(rs.getString(1));
//        s.close();
        if (oldData != null) {
            String oldValue = getOldValue(rs.getString(1), oldData);
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                ViewTestComboBox res = list.get(i);
                if (res.getId().equals(oldValue)) {
                    toReturn.setSelectedIndex(i);
                }
            }
        } else if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                ViewTestComboBox res = list.get(i);
                if (res.getId().equals(oldValue)) {
                    toReturn.setSelectedIndex(i);
                }
            }
        }
        if (ComponentsToPanel.isHaveSubFields(tableName, rs.getString("COLUMN_NAME"))) {
            toReturn.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    JComboBox jcb = (JComboBox) e.getSource();
                    ComponentGenerator.toEnableField(ComponentsToPanel.getListSubFields(tableName, jcb.getName(), jcb.getSelectedItem().toString()));
                }
            });
        }
//        s.close();
        return toReturn;
    }


    public static JComponent getComponentCBForQuestionnaire(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        /*
       This method create JComboBox for next tables: volunteers, probationers, groups.
        */
        Connection s = DbUtils.getDBConnectionGeneral();
//        System.out.println(rs.getString("REFERENCED_TABLE_NAME"));
        PreparedStatement ps = s.prepareStatement("SELECT * FROM " + rs.getString("REFERENCED_TABLE_NAME") +
                " ORDER BY " + SGTTestParametrs.getInstance().getCurrentLocal().getColumn());
//        System.out.println("ps: "+ps.toString());
        ResultSet rs2 = ps.executeQuery();
        List<ViewTestComboBox> list = new ArrayList<ViewTestComboBox>();
        while (rs2.next()) {
            ViewTestComboBox ctc = new ViewTestComboBox.Build()
                    .id(rs2.getString(1))
                    .nameRu(rs2.getString("name_ru"))
                    .nameEn(rs2.getString("name_en"))
                    .nameKz(rs2.getString("name_kk"))
                    .build();
            list.add(ctc);
        }

        JComboBox toReturn = new JComboBox(list.toArray());
        toReturn.setName(rs.getString(1));
//        s.close();
        if (oldData != null) {
            String oldValue = getOldValue(rs.getString(1), oldData);
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                ViewTestComboBox res = list.get(i);
                if (res.getId().equals(oldValue)) {
                    toReturn.setSelectedIndex(i);
                }
            }
        } else if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                ViewTestComboBox res = list.get(i);
                if (res.getId().equals(oldValue)) {
                    toReturn.setSelectedIndex(i);
                }
            }
        }
        return toReturn;
    }


    public static JComponent getComponentCBCode(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        Connection s = DbUtils.getDBConnectionGeneral();
        PreparedStatement ps = s.prepareStatement("SELECT * FROM " + rs.getString("REFERENCED_TABLE_NAME"));
        ResultSet rs2 = ps.executeQuery();
        List<ViewTestComboBox> list = new ArrayList<ViewTestComboBox>();
        while (rs2.next()) {
            ViewTestComboBox ctc = new ViewTestComboBox.Build()
                    .id(rs2.getString(1))
                    .nameRu(rs2.getString(2))
                    .nameEn(rs2.getString(2))
                    .nameKz(rs2.getString(2))
                    .build();
            list.add(ctc);
        }

        JComboBox toReturn = new JComboBox(list.toArray());
        toReturn.setName(rs.getString("COLUMN_NAME"));
        if (rs.getString("TABLE_NAME").equals("probationers")
                && (rs.getString("COLUMN_NAME").equals("group_id") || rs.getString("COLUMN_NAME").equals("volunteer_id"))) {
            toReturn.setEnabled(false);
        }
//        s.close();
        if (oldData != null) {
            String oldValue = getOldValue(rs.getString("COLUMN_NAME"), oldData);
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                ViewTestComboBox res = list.get(i);
                if (res.getId().equals(oldValue)) {
                    toReturn.setSelectedIndex(i);
                }
            }
        } else if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                ViewTestComboBox res = list.get(i);
                if (res.getId().equals(oldValue)) {
                    toReturn.setSelectedIndex(i);
                }
            }
        }
        if (rs.getString("TABLE_NAME").equals("probationers") & rs.getString("COLUMN_NAME").equals("volunteer_id")) {
            toReturn.addActionListener(ListenerFactory.setProbationerCodeEqualsVolunteerCode());
        }
        return toReturn;
    }

    public static JComponent getComponentRB(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        final JPanel radioPanel = new JPanel(new GridLayout(1, 2, 3, 5));
        final JRadioButton rb1 = new JRadioButton(Localisation.getMessage("form.yes"));
        final JRadioButton rb2 = new JRadioButton(Localisation.getMessage("form.no"));
        rb2.setSelected(true);
        ButtonGroup bg = new ButtonGroup();
        radioPanel.add(rb1);
        radioPanel.add(rb2);
        bg.add(rb1);
        bg.add(rb2);
        radioPanel.setName(rs.getString(1));
        if (oldData != null) {
            String oldValue = getOldValue(rs.getString(1), oldData);
            if (oldValue.equals("1")) {
                rb1.setSelected(true);
            }
            if (oldValue.equals("0")) {
                rb2.setSelected(true);
            }
        } else if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            if (oldValue.equals("1")) {
                rb1.setSelected(true);
            }
            if (oldValue.equals("0")) {
                rb2.setSelected(true);
            }
        }

        return radioPanel;
    }

    public static JComponent getComponentTA(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        JTextArea tf = new JTextArea(5, 25);
        tf.setName(rs.getString("COLUMN_NAME"));
        tf.setBorder(LineBorder.createBlackLineBorder());
        tf.setAutoscrolls(true);
        tf.setLineWrap(true);
        if (oldData != null) {
            String oldValue = getOldValue(rs.getString(1), oldData);
            tf.setText(oldValue);
        } else if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            tf.setText(oldValue);
        }
        return tf;
    }

    public static JComponent getComponentDT(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        JPanel datePanel = new JPanel();
        datePanel.setName(rs.getString("COLUMN_NAME"));
        JFormattedTextField dateField = new JFormattedTextField(new SimpleDateFormat("dd-MM-yyyy"));
        dateField.setName(rs.getString("COLUMN_NAME"));
        dateField.setColumns(8);
        dateField.setEditable(false);
        if (obj != null) {
            String oldValue = StaticMethods.returnNotFormatedData(getOldValueOfObject(rs, obj));
            dateField.setText(oldValue);
        }
//        ImageIcon icon = new ImageIcon("src/images/Calendar-icon.png");
        String path = "images/Calendar-icon.png";
        URL imgURL = ComponentsToPanel.class.getResource(path);
        ImageIcon icon = new ImageIcon(imgURL);
        JButton calendarButton = new JButton(icon);
        calendarButton.setPreferredSize(
                new Dimension(icon.getIconWidth(),
                        icon.getIconHeight()));
        calendarButton.setToolTipText(Localisation.getMessage("tip.clickme"));
        calendarButton.addActionListener(ListenerFactory.getFrameCalendar(dateField));
        datePanel.add(dateField, BorderLayout.WEST);
        datePanel.add(calendarButton, BorderLayout.EAST);
        return datePanel;
    }

    public static JComponent getComponentFileChooser(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        UserDefineJFileChooserWithView userDefineJFileChooser;
        DbFile dbFile=null;
        File file=null;
        if(oldData.size()<1){
            userDefineJFileChooser=new UserDefineJFileChooserWithView("images/camera_test_7074.png", "images/cross_script.png",null);  
        }else {
            String oldValue = getOldValue(rs.getString(1), oldData);
            if(oldValue!=null){
                String pathToDir= VolunteerSelectorController.viewProbationer.getProbationCode()+"\\"+ InputFormDisplay.getViewAnalysis().getAnalysisName()+"\\";
                dbFile=DbFile.getDbFileById(Integer.valueOf(oldValue));
                file=new File(AppSettings.get("generalSettings", "saveFileTo", "").toString()+"\\"+pathToDir+dbFile.getFileName()+"."+dbFile.getFileEhtension());
            }
            if(file==null || dbFile.getFileId()<1){
               userDefineJFileChooser=new UserDefineJFileChooserWithView("images/camera_test_7074.png", "images/cross_script.png",null);
            }else{
               userDefineJFileChooser=new UserDefineJFileChooserWithView("images/camera_test_7074.png", "images/cross_script.png", file);
            }

        }
        
        userDefineJFileChooser.setName(rs.getString("COLUMN_NAME"));
        return userDefineJFileChooser;
    }

    public static JComponent getComponentJLB(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        JLabel lb = new JLabel(rs.getString(SGTTestParametrs.getInstance().getCurrentLocal().getColumn()));
        lb.setName(rs.getString("COLUMN_NAME"));
        return lb;
    }

    public static JComponent getComponentJTF(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        JTextField jtf = new JTextField(5);
        jtf.setName(rs.getString("COLUMN_NAME"));
        if (jtf.getName().equals("volunteer_code") /*|| jtf.getName().equals("probationer_code")*/) {
            jtf.setInputVerifier(ComponentsToPanel.setVolunteerCodeValidator());

        } else if (jtf.getName().equals("probationer_code")) {
            jtf.setEditable(false);
        } else {
            jtf.addFocusListener(ListenerFactory.checkFormL());
        }
        if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            jtf.setText(oldValue);
        }

        return jtf;
    }

    public static JComponent getComponentFN(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        NumberFormat nf = NumberFormat.getIntegerInstance();
        JFormattedTextField intField = new JFormattedTextField(nf);
        intField.setName(rs.getString("COLUMN_NAME"));
        intField.setColumns(5);
        intField.setInputVerifier(ComponentsToPanel.setNumberValidator());
        if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            intField.setText(oldValue);
        }
        return intField;
    }

    public static JComponent getComponentFDN(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(1);
        JFormattedTextField doubleField = new JFormattedTextField(nf);
        doubleField.setName(rs.getString("COLUMN_NAME"));
        doubleField.setColumns(5);
        doubleField.setInputVerifier(ComponentsToPanel.setDoubleValidator());
        if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            doubleField.setText(oldValue);
        }
        return doubleField;
    }

    public static JComponent getComponentEMAIL(ResultSet rs, Vector<Vector<Object>> oldData, Object obj) throws Exception {
        JTextField emailField = new JTextField(5);
        emailField.setName(rs.getString("COLUMN_NAME"));
        emailField.setInputVerifier(ComponentsToPanel.setEmailValidator());
        if (obj != null) {
            String oldValue = getOldValueOfObject(rs, obj);
            emailField.setText(oldValue);
        }
        return emailField;
    }

    private static String getOldValue(String parameterName, Vector<Vector<Object>> oldData) throws SQLException {
        String toReturn = "";
        if (oldData != null) {
            for (int i = 1, oldDataSize = oldData.size(); i < oldDataSize - 1; i++) {
                Vector res = oldData.get(i);
                ViewAnalysis va = (ViewAnalysis) res.get(0);
                if (va.getAnalysisName().equals(parameterName)) {
                    if(res.get(1)!=null){
                        toReturn = res.get(1).toString();
                    }

                }
            }
        }
        return toReturn;
    }

    public static String getOldValueOfObject(ResultSet rs, Object obj) throws SQLException {
        String toReturn = "";
        if (!rs.getString("FIELD_TYPE").equals("SKIP_ELEMENT") || !rs.getString("FIELD_TYPE").equals("AUTO_INCREMENT")) {
            try {
//            toReturn= Volunteer.getMapVolunteersFields().get(rs.getString(1)).getValue((Volunteer)obj);
//            toReturn= EVolunteerFields.valueOf(rs.getString(1).toUpperCase()).getValue((Volunteer)obj);
                DbTable dbTable = (DbTable) obj;
                toReturn = dbTable.getMapValuesFields().get(rs.getString(1));
            } catch (NullPointerException exp) {
                exp.printStackTrace();
            }
        }
        return toReturn;
    }
}
